/*******************************************************************************
 * KindEditor - WYSIWYG HTML Editor for Internet
 * Copyright (C) 2006-2011 kindsoft.net
 *
 * @author Roddy <luolonghao@gmail.com>
 * @site http://www.kindsoft.net/
 * @licence http://www.kindsoft.net/license.php
 *******************************************************************************/

KindEditor.plugin('uploadimage', function(K) {
    var self = this, name = 'image',
            allowImageUpload = K.undef(self.allowImageUpload, true),
            allowImageRemote = K.undef(self.allowImageRemote, true),
            formatUploadUrl = K.undef(self.formatUploadUrl, true),
            allowFileManager = K.undef(self.allowFileManager, false),
            uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
            remoteImageLocal = K.undef(self.remoteImageLocal, false),
            remoteImageLocalUrl = K.undef(self.remoteImageLocalUrl, ""),
            imageTabIndex = K.undef(self.imageTabIndex, 0),
            imgPath = self.pluginsPath + 'uploadimage/images/',
            extraParams = K.undef(self.extraFileUploadParams, {}),
            filePostName = K.undef(self.filePostName, 'imgFile'),
            fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false),
            lang = self.lang(name + '.');

    self.plugin.imageDialog = function(options) {
        var imageUrl = options.imageUrl,
                tabIndex = K.undef(options.tabIndex, 0),
                clickFn = options.clickFn;
        var target = 'kindeditor_upload_iframe_' + new Date().getTime();
        var hiddenElements = [];
        for (var k in extraParams) {
            hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
        }
        var html = [
            '<div style="padding:20px;">',
            //tabs
            '<div class="tabs"></div>',
            //remote image - start
            '<div class="tab1" style="display:none;">',
            //url
            '<div class="ke-dialog-row">',
            '<label for="remoteUrl" style="width:60px;">' + lang.remoteUrl + '</label>',
            '<input type="text" id="remoteUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> &nbsp;',
            '<span class="ke-button-common ke-button-outer">',
            '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
            '</span> &nbsp;',
            '<span class="ke-button-common ke-button-outer">',
            '<input type="button" class="ke-button-common ke-button" name="viewBaidu" value="' + lang.viewBaidu + '" />',
            '</span>',
            '</div>',
            '</div>',
            //remote image - end
            //local upload - start
            '<div class="tab2" style="display:none;">',
            '<iframe name="' + target + '" style="display:none;"></iframe>',
            '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + K.addParam(uploadJson, 'dir=image') + '">',
            //file
            '<div class="ke-dialog-row">',
            hiddenElements.join(''),
            '<label style="width:60px;">' + lang.localUrl + '</label>',
            '<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> &nbsp;',
            '<input type="button" class="ke-upload-button" value="' + lang.upload + '" />',
            '</div>',
            '</form>',
            '</div>',
            //local upload - end
            '</div>'
        ].join('');
        var dialogWidth = 450,
                dialogHeight = 200;
        var dialog = self.createDialog({
            name: name,
            width: dialogWidth,
            height: dialogHeight,
            title: self.lang(name),
            body: html,
            yesBtn: {
                name: self.lang('yes'),
                click: function(e) {
                    // Bugfix: http://code.google.com/p/kindeditor/issues/detail?id=319
                    if (dialog.isLoading) {
                        return;
                    }
                    // insert local image
                    if (tabs && tabs.selectedIndex === 1) {
                        if (uploadbutton.fileBox.val() == '') {
                            alert(self.lang('pleaseSelectFile'));
                            return;
                        }
                        dialog.showLoading(self.lang('uploadLoading'));
                        uploadbutton.submit();
                        localUrlBox.val('');
                        return;
                    }
                    // insert remote image
                    var url = K.trim(urlBox.val());
                    if (url == 'http://' || K.invalidUrl(url)) {
                        alert(self.lang('invalidUrl'));
                        urlBox[0].focus();
                        return;
                    }
                    //本地化
                    if (remoteImageLocal && url.indexOf("://") > 0) {
                        dialog.showLoading(self.lang('uploadLoading'));
                        $.ajax({
                            type: "get",
                            url: remoteImageLocalUrl,
                            data: {url: url},
                            success: function(data) {
                                dialog.hideLoading();
                                if (data.error === 0) {
                                    clickFn.call(self, data.url);
                                } else {
                                    alert(data.message);
                                }
                            },
                            error: function(html) {
                                dialog.hideLoading();
                                self.errorDialog(html);
                            },
                            dataType: 'json',
                            global: false
                        });
                        return;
                    }
                    clickFn.call(self, url);
                }
            },
            beforeRemove: function() {
                viewServerBtn.unbind();
                viewBaiduBtn.unbind();
            }
        }),
                div = dialog.div;

        var urlBox = K('[name="url"]', div),
                localUrlBox = K('[name="localUrl"]', div),
                viewServerBtn = K('[name="viewServer"]', div),
                viewBaiduBtn = K('[name="viewBaidu"]', div);

        var tabs;

        tabs = K.tabs({
            src: K('.tabs', div),
            afterSelect: function(i) {
            }
        });
        tabs.add({
            title: lang.remoteImage,
            panel: K('.tab1', div)
        });
        tabs.add({
            title: lang.localImage,
            panel: K('.tab2', div)
        });
        tabs.select(tabIndex);


        var uploadbutton = K.uploadbutton({
            button: K('.ke-upload-button', div)[0],
            fieldName: filePostName,
            form: K('.ke-form', div),
            target: target,
            width: 60,
            afterUpload: function(data) {
                dialog.hideLoading();
                if (data.error === 0) {
                    var url = data.url;
                    if (formatUploadUrl) {
                        url = K.formatUrl(url, 'absolute');
                    }
                    if (self.afterUpload) {
                        self.afterUpload.call(self, url, data, name);
                    }
                    if (!fillDescAfterUploadImage) {
                        clickFn.call(self, url, data.title, data.width, data.height, data.border, data.align);
                    } else {
                        K(".ke-dialog-row #remoteUrl", div).val(url);
                        K(".ke-tabs-li", div)[0].click();
                        K(".ke-refresh-btn", div).click();
                    }
                } else {
                    alert(data.message);
                }
            },
            afterError: function(html) {
                dialog.hideLoading();
                self.errorDialog(html);
            }
        });
        uploadbutton.fileBox.change(function(e) {
            localUrlBox.val(uploadbutton.fileBox.val());
        });
        if (allowFileManager) {
            viewServerBtn.click(function(e) {
                self.loadPlugin('filemanager', function() {
                    self.plugin.filemanagerDialog({
                        viewType: 'VIEW',
                        dirName: 'image',
                        clickFn: function(url, filename) {
                            if (self.dialogs.length > 1) {
                                K('[name="url"]', div).val(url);
                                if (self.afterSelectFile) {
                                    self.afterSelectFile.call(self, url, filename);
                                }
                                self.hideDialog();
                            }
                        }
                    });
                });
            });
        } else {
            viewServerBtn.hide();
        }

        viewBaiduBtn.click(function(e) {
            self.loadPlugin('baiduimage', function() {
                self.plugin.baiduimageDialog({
                    clickFn: function(url, filename) {
                        if (self.dialogs.length > 1) {
                            K('[name="url"]', div).val(url);
                            if (self.afterSelectFile) {
                                self.afterSelectFile.call(self, url, filename);
                            }
                            self.hideDialog();
                        }
                    }
                });
            });
        });

        urlBox.val(options.imageUrl);

        if (tabIndex === 0) {
            urlBox[0].focus();
            urlBox[0].select();
        }
        return dialog;
    };
});
